<template>
  <view class="container">
    <view 
      class="patient-item" 
      v-for="(item, index) in patientList" 
      :key="item.id" 
      @click="handleSelectPatient(item)" 
      @longpress="showDeleteMenu(index)"
      :class="{selected: item.id === currentPatientId}"  
    >
      <view class="patient-name">
        {{ item.name }}
        <text class="patient-type">{{ item.memberRelationship }}</text> <!-- 修改字段名 -->
        <uni-icons 
          v-if="item.id === currentPatientId" 
          type="checkmark" 
          color="#007AFF" 
          size="24"
        ></uni-icons>  
      </view>
      <view class="patient-info">
        {{ item.gender }} {{ calculateAge(item.birthDate) }}岁 {{ item.phone }} <!-- 修改字段名并计算年龄 -->
      </view>
    </view>
    <button class="add-btn" @click="navigateToAdd">添加就诊人</button>
  </view>
</template>

<script>
// 导入API模块
import api from '@/api/index.js'

export default {
  data() {
    return {
      patientList: [],
      currentPatientId: null  // 当前选中患者ID
    };
  },
  onShow() {
    this.loadPatients();
    this.loadCurrentPatient();  // 加载当前选中患者
  },
  methods: {
    // 计算年龄
    calculateAge(birthDate) {
      if (!birthDate) return '';
      const birthYear = new Date(birthDate).getFullYear();
      const currentYear = new Date().getFullYear();
      return currentYear - birthYear;
    },
    
    // 加载当前选中患者
    loadCurrentPatient() {
      const currentPatient = uni.getStorageSync('currentPatient');
      this.currentPatientId = currentPatient?.id || null;
    },
    
    // 处理患者选择
    handleSelectPatient(patient) {
      uni.setStorageSync('currentPatient', patient);
      this.currentPatientId = patient.id;
      uni.$emit('patientChanged', patient);  // 触发全局事件
      
      // 返回就诊记录页
      const pages = getCurrentPages();
      if (pages.length > 1) {
        uni.navigateBack();
      }
    },
    
    // 从后端加载患者数据
    async loadPatients() {
      try {
        uni.showLoading({ title: '加载中...' });
        
        const res = await api.getPatientsApi();
        
        console.log('API返回原始数据:', res); // 添加调试信息
        
        // 适配后端返回的数据格式
        if (res && res.code === 200) {
          this.patientList = res.data || [];
          console.log('处理后的患者列表:', this.patientList);
        } else {
          this.patientList = [];
          console.error('API返回非成功状态:', res);
        }
      } catch (error) {
        console.error('获取患者列表失败:', error);
        this.patientList = [];
      } finally {
        uni.hideLoading();
      }
    },
    
    navigateToAdd() {
      uni.navigateTo({
        url: '/pageMember/setting/add-patient/add-patient'
      });
    },

    // 编辑导航方法
    navigateToEdit(index) {
        // 传递患者ID
        const patient = this.patientList[index];
        uni.navigateTo({
            url: `/pageMember/setting/add-patient/add-patient?patientId=${patient.id}`
        });
    },

   // 显示操作菜单
    showDeleteMenu(index) {
        uni.showActionSheet({
            itemList: ['编辑就诊人', '删除就诊人'],
            itemColor: '#ff4d4f',
            success: (res) => {
                if (res.tapIndex === 0) {
                    this.navigateToEdit(index); // 编辑操作
                } else if (res.tapIndex === 1) {
                    this.confirmDelete(index); // 删除操作
                }
            }
        });
    },
    
    // 确认删除
    confirmDelete(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除该就诊人吗？',
        success: (res) => {
          if (res.confirm) {
            this.deletePatient(index);
          }
        }
      });
    },
    
    // 调用API删除患者
    async deletePatient(index) {
      try {
        const patient = this.patientList[index];
        // 调用删除API
        await api.deletePatientApi(patient.id);
        
        // 更新本地列表
        this.patientList.splice(index, 1);
        
        uni.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 1500
        });
      } catch (error) {
        console.error('删除患者失败:', error);
        uni.showToast({
          title: '删除失败: ' + (error.message || '未知错误'),
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style>
/* 保持原有的样式 */
.patient-item.selected {
  border: 2rpx solid #007AFF;
  background-color: #f0f8ff;
}

.patient-name {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.container {
  padding: 20rpx;
}

.patient-item {
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.patient-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.patient-type {
  font-size: 24rpx;
  color: #007AFF;
  margin-left: 10rpx;
}

.patient-info {
  font-size: 28rpx;
  color: #666;
}

.add-btn {
  margin-top: 40rpx;
  background-color: #007AFF;
  color: #fff;
  font-size: 32rpx;
  border-radius: 10rpx;
}
</style>